<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Company extends MY_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('company_model');	
		$this->load->model('rate_model');	
	}
	
	public function index()
	{
		$data['msg'] 	= NULL;
		//$data['result'] = $this->company_model->where('deleted',0)->find_all();
		//print_r($this->db->last_query());
		$this->load->view('company/main', $data);
	}
	
		
	function form($id=NULL)
	{
		//sleep(1);
		$data='';
		$data['company']='';
		
		if(!empty($id))
			$data['company'] = $this->company_model->find($id);
			
		$this->load->view('company/form', $data);
	}
	
	
	function create($form)
	{
		if($inserted_id = $this->company_model->insert($form))
			{
				$data['error']= false;
				$data['id']= $inserted_id;
				$data['msg']  = '<span style="color:green">New Company :<b>"'.$form['name'].'"</b> Has Been Added Successfully<br>Thanks You !</span>';
			}
			else{
				$data['error']= true;
				$data['msg']  = 'Data Base Error <br> ERROR: com/ins/100';
			}
			
		return $data;
	}
	
	
	function edit($id,$form)
	{
		if($this->company_model->update($id, $form)){
					$data['error']= false;
					$data['msg']= $form['name'].' Successfully Updated..';
				}
				else{
					$data['error']= true;
					$data['msg']  = 'Data Base Error <br> ERROR: com/upd/101';
				}
			
		return $data;
	}
	
	
	public function save()
	{
		$this->form_validation->set_message('is_unique', "The<b> %s </b>already Exist!");
		$this->form_validation->set_message('is_unique2', "The<b> %s </b>already Exist!");
		
		//check if it new record or update to set the validation rules
		$id = $this->input->post('id');
		//insert
		if(empty($id) && $id=='')
		{
		$this->form_validation->set_rules('name'	, 'Company Name', 'trim|required|min_length[3]|max_length[255]|is_unique[company.name]');
		$this->form_validation->set_rules('phone1'	, 'Phone 1'		, 'trim|required|max_length[20]|min_length[5]|is_unique[company.phone1]');
		$this->form_validation->set_rules('phone2'	, 'Phone 2'		, 'trim|max_length[20]|min_length[5]|is_unique[company.phone2]');
		$this->form_validation->set_rules('phone3'	, 'Phone 3'		, 'trim|max_length[20]|min_length[5]|is_unique[company.phone3]');
		$this->form_validation->set_rules('fax1'	, 'Fax 1'		, 'trim|max_length[20]|min_length[5]|is_unique[company.fax1]');
		$this->form_validation->set_rules('fax2'	, 'Fax 2'		, 'trim|max_length[20]|min_length[5]|is_unique[company.fax2]');
		$this->form_validation->set_rules('website'	, 'website'		, 'trim|prep_url|is_unique[company.website]');
		$this->form_validation->set_rules('email'	, 'Company Email','valid_email|trim|is_unique[company.email]');
		}
		
		//update
		if($id && !empty($id))
		{
		//$this->form_validation->set_rules('username', 'User', 'is_unique[t_users.username.id.'.$id.']'); 
		$this->form_validation->set_rules('name'	, 'Company Name', 'trim|required|min_length[3]|max_length[255]|is_unique2[company.name.id.'.$id.']');
		$this->form_validation->set_rules('phone1'	, 'Phone 1'		, 'trim|required|max_length[20]|min_length[5]|is_unique2[company.phone1.id.'.$id.']');
		$this->form_validation->set_rules('phone2'	, 'Phone 2'		, 'trim|max_length[20]|min_length[5]|is_unique2[company.phone2.id.'.$id.']');
		$this->form_validation->set_rules('phone3'	, 'Phone 3'		, 'trim|max_length[20]|min_length[5]|is_unique2[company.phone3.id.'.$id.']');
		$this->form_validation->set_rules('fax1'	, 'Fax 1'		, 'trim|max_length[20]|min_length[5]|is_unique2[company.fax1.id.'.$id.']');
		$this->form_validation->set_rules('fax2'	, 'Fax 2'		, 'trim|max_length[20]|min_length[5]|is_unique2[company.fax2.id.'.$id.']');
		$this->form_validation->set_rules('website'	, 'website'		, 'trim|prep_url|is_unique2[company.website.id.'.$id.']');
		$this->form_validation->set_rules('email'	, 'Company Email','valid_email|trim|is_unique2[company.email.id.'.$id.']');
		}
		

		$this->form_validation->set_rules('country'	, 'Country'		, 'trim|required|max_length[2]|alpha');
		$this->form_validation->set_rules('city'	, 'City'		, 'trim|required|max_length[255]|min_length[3]');
		$this->form_validation->set_rules('address1', 'Address 1'	, 'trim|min_length[5]');
		$this->form_validation->set_rules('address2', 'Address 2'	, 'trim|min_length[5]');
		$this->form_validation->set_rules('notes'	, 'Notes'		, 'trim|min_length[5]');
		

		
		if ($this->form_validation->run() == FALSE)
		{
			$data['error']= true;
			$data['msg']  = $this->form_validation->getErrorsArray();
			
			die(json_encode($data));

			//die(json_encode($errors));
		}
		else
		{
			//ucwords(strtolower($bar));
			$form['name'] 		= ucwords(strtolower($this->input->post('name')));
			$form['country'] 	= $this->input->post('country');
			$form['city'] 		= ucwords(strtolower($this->input->post('city')));
			$form['phone1'] 	= $this->input->post('phone1');
			$form['phone2'] 	= $this->input->post('phone2');
			$form['phone3'] 	= $this->input->post('phone3');
			$form['fax1'] 		= $this->input->post('fax1');
			$form['fax2'] 		= $this->input->post('fax2');
			$form['website'] 	= $this->input->post('website');
			$form['email'] 		= $this->input->post('email');
			$form['address1'] 	= ucwords(strtolower($this->input->post('address1')));
			$form['address2'] 	= ucwords(strtolower($this->input->post('address2')));
			$form['notes'] 		= ucwords(strtolower($this->input->post('notes')));
			
			//NEW Company
			if($this->input->post('id')=='')
			{
				$data = $this->create($form);
				$this->log('Company', 'Created record with ID: '.$data['id'].' : '.$this->session->userdata['ip_address']);
			}
			
			//Edit Company
			if($this->input->post('id'))
			{
				$id = $this->input->post('id');
				$data = $this->edit($id, $form);
				$this->log('Company', 'Updated record with ID: '.$id.' : '.$this->session->userdata['ip_address']);
			}
			
			
			die(json_encode($data));
		}
	}
	
	function delete($id=NULL)
	{

		
		if (!empty($id))
		{	
		/* Before the delete check if there is any attached contacts on the contacts table.
		* If there is any contacts return error
		* Else perform the delete funtion. 
		*/	
			$com_count = $this->company_model->find_count($id);
			if($com_count>0)
			{
				//failed to delete
					$data['error']	= true;
					$data['msg']	= ' You can not delete this company since there is a contacts attached to it<br><br><b>'.$com_count.' Contact(s) assigns to it.</b><br>ERROR: com/del/102';
					die(json_encode($data));
			}
			
				if ($del = $this->company_model->delete($id))
				{
					//success
					//Warning if there is any attached contacts to this company
					if(is_string($del)){
						$data['msg'] 	= $del;
						$data['error']	= true;
					}else{
						$data['msg']	= ' Successfully Deleted..';
						$data['error']	= false;
						$this->log('Company', 'Delete record with ID: '.$id.' : '.$this->session->userdata['ip_address']);
					}

				}
				else{
					//failed to delete
					$data['error']	= true;
					$data['msg']	= ' Failed to Delete..';
				}
		die(json_encode($data));
		}
		
	}
	
	
	function get_company_info($id=NULL){
		if(!$id)
		{
			$com_list = $this->company_model->where('deleted',0)->find_all();
			$contact_group = array();
			//$data['num_row'] = $com_list->num_rows();

			foreach($com_list as $row){
				$contact_group[mb_substr($row->name,0,1,'utf-8')][] = array("id" => $row->id, "name" => $row->name);
			}
			
			$data['com_list']=$contact_group;
		}
		
		if($id)
		{
			$this->log('Company', 'View record with ID: '.$id.' : '.$this->session->userdata['ip_address']);
			$data['com_list']  	= $this->company_model->find($id);
		}

		die(json_encode($data['com_list']));
		
	}
	
	//Returns the count number of contacts for a given company.
	function get_company_counts($id=NULL)
	{
		//sleep(1);
		$data['com_count'] = $this->company_model->find_count($id);
		die(json_encode($data));
	}
	
	//Allow User To View the Rate and see the avarage rate for the companies
	function get_company_rate($id=NULL)
	{
		//sleep(1);
		$data['rate']  		= $this->rate_model->avg_company($id);
		$data['rate_count'] = $this->rate_model->count_rates_per_company($id);
		die(json_encode($data));
	}
}

